# -*- coding: utf-8 -*-..,
##############################################################################
#
#    @author: PhongND
#    Copyright (C) 2014 Crea8s (http://www.crea8s.com) All Rights Reserved.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
from openerp import tools

import pytz
import tzlocal
from tzlocal import get_localzone # $ pip install tzlocal
# test 1: ...?
import xmlrpclib
import socket
import magento
import magento_api
from magento_api.core_api import Core, OrderConfig
from website import Website, Store, View     
from delivery import Delivery     

# test 2: XMLRPC
import traceback
import sys
from xmlrpclib import ServerProxy, Error

# product, sale
import product
import urllib
import urllib2
import base64
import io

# for logging
from StringIO import StringIO
import logging
_logger = logging.getLogger(__name__)

# mapping, but NONONO, (by: session.context??)
# from openerp.addons.connector.unit.mapper import (Mapper,
#                                                   ImportMapper,
#                                                   ExportMapper, 
#                                                   mapping, 
#                                                   )
# from openerp.addons.connector.connector import (Environment,
#                                                 )
#                                                   
# from openerp.addons.connector.backend_model import (connector_backend,
#                                                 )


#  testing...
# import tests AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

# from tests import test_product



class crea8s_magento(osv.osv):
    _name = "crea8s.magento"
    _description = 'crea8s_magento...'
    _columns = {
        'name': fields.char('crea8s_magento..', size=100),
# 		'date': fields.date('Date'),
        
# 'state': fields.selection([('draft','Draft'),
# ('confirmed','Confirmed')],'State',required=True,readonly=True)
    }
#     _rec_name = 'partner_id' # ???
#     _auto = False # okok, ??? this object is for reporting purpose.
       
    strFormatTime = '%Y-%m-%d %H:%M:%S %Z'
    def act_helloword(self, cr, uid, ids, context={}):
       return self.write(cr, uid, ids, {'name': 'Hello word ! - PhongND said: "cr, uid, ids"'})
    
crea8s_magento()


class Instance(orm.Model):  # osv.osv; ??,orm.Model
    _name = "crea8s.magento.instance"
#     _inherit = 'connector.backend'  # from class: connector_backend(orm.AbstractModel)
    _description = 'crea8s.magento.instance...'
    _columns =dict(
        name=fields.char(
            'Name', required=True, size=50),
        url=fields.char(
            'Magento Site URL', required=True, size=255),
        api_user=fields.char(
            'xmlrpc Username', required=True, size=50),
        api_key=fields.char(
            'xmlrpc Password', required=True, size=100),
        order_prefix=fields.char(
            'Sale Order Prefix', size=10,
            help="This helps to distinguish between "
                 "orders from different instances"
        ),
        active=fields.boolean('Active'), # AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        company=fields.many2one(
            'res.company', 'Company', required=True),
        category=fields.many2one(
            'product.category', 'Root Category'),
        websites=fields.one2many('crea8s.magento.website', 'instance', 'Website', 
            readonly=True, ),

#         order_states=fields.one2many(
#             'magento.order_state', 'instance', 'Order States',
#         ),
#         carriers=fields.one2many(
#             'magento.instance.carrier', 'instance',
#             'Carriers / Shipping Methods'
#         ),
        
        version=fields.selection([('1.7','Version 1.7')],'Magento Version',required=True),
    )
    
    

#     _rec_name = 'partner_id' # ???
#     _auto = False # okok, ??? this object is for reporting purpose.
       
    strFormatTime = '%Y-%m-%d %H:%M:%S %Z'
    def act_helloword(self, cr, uid, ids, context={}):
        return self.write(cr, uid, ids, {'name': 'Hello word ! - PhongND said: "cr, uid, ids"'})
    
    def unlink(self, cr, uid, ids, context=None):
        arrORMs = self.browse(cr, uid, ids, context=context)
        unlink_ids = []
        boRemove = True
        for item in arrORMs:
            if item.websites:
#                 if count(item.stores) > 0:
#                 if count(item.stores, lambda p: p.id) > 0:  # nonono
                if  sum(p.id for p in item.websites) > 0:
                    boRemove = False
            if boRemove == True:
                unlink_ids.append(item.id)
    
        if boRemove == False:
            raise osv.except_osv(_('Invalid Action!'), _('Can not remove any items, because there\'re its childs.'))
        else:
            return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
        
    def test_connection(self, cr, uid, ids, context={}):
        try:
            instance = self.browse(cr, uid, ids[0], context)
            arrServerInfo = [instance.url, instance.api_user, instance.api_key]
            
            
            with magento.API(
            instance.url, instance.api_user, instance.api_key
            ) as mgAPI:  
                mgAPI.connect()
                mgAPI.__enter__()
                _logger.info('test_connection01-info: SUCCESS01') 
#                 buff = StringIO()
#                 traceback.print_exc(file=buff)
                raise osv.except_osv(
                _('Success!'),
                _('Test connection successfully.')
                )
            
                return True
            # test product
            #            objTestProduct = TetProduct()
            #            objTestProduct.test_0020_import_simple_product()
            
            return True

        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            _logger.info('test_connection01-info: FALSE')
            _logger.debug('test_connection01-debug: FALSE')
            _logger.error('test_connection01-error: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())

            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def test_connection.')
                )
        
        
        
        return True

    
    def test_connection02(self, cr, uid, ids, context={}):
        print 'test_connection02'
        try:
            instance = self.browse(cr, uid, ids[0], context)
            server_address = instance.url
            if not server_address[-1:] == '/':
                server_address = server_address + "/"
            server_address = server_address + "index.php/api/xmlrpc/?wsdl"
            server = ServerProxy(server_address)
            session = server.login(instance.api_user, instance.api_key)
            print '+ success!'
            _logger.info('test_connection02-info: success with user %s', instance.api_user)
            _logger.debug('test_connection02-debug: success with user %s', instance.api_user)
            print '+ success!02'
            
            return [True, server, session] 
        
        except:
            traceback.print_exc()
            print '+ fail!'
            _logger.info('test_connection02-info: FALSE')
            return [False, sys.exc_info()[0], False]
        
        return True

    def import_website(self, cr, uid, ids, context={}):
        
        ormWebsite = self.pool.get('crea8s.magento.website')
        ormWebsite2 = self.pool.get('crea8s.magento.website')
        ormStore = self.pool.get('crea8s.magento.store')
        ormView = self.pool.get('crea8s.magento.view')

# Create websites  ?????.
# 1. nono-aaa, okok; cause: Core (not 02) ????? nonononono nonononono nonononono nonononono aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
# 2. okok, cause: raise osv.except_osv(... 
        try:
            instance = self.browse(cr, uid, ids[0], context)
            print 'instance: ' + str(instance)
            with magento_api.core_api.Core(
                instance.url, instance.api_user, instance.api_key
            ) as websiteAPI:
                mag_websites = websiteAPI.websites()
                arrWebsite_ids = []
                # Create websites
                for mag_website in mag_websites:
                    iID = ormWebsite.find_or_create(cr, uid, instance.id, mag_website, context)
                    arrWebsite_ids.append(iID) #mag_website['name']
                 
                print '+ ' +  _('Import website successfully.') # + str(mag_websites)
                 
#                 # create stores follow website
                mag_stores = []
                store_ids = []
                for website in ormWebsite.browse(
                    cr, uid, arrWebsite_ids, context=context):
                    mag_stores = websiteAPI.stores(
                        {'website_id': {'=': website.magento_id}}
                    )
                      
                    # Create stores
                    for mag_store in mag_stores:
                        store_ids.append(ormStore.find_or_create(
                            cr, uid, website.id, mag_store, context
                        ))
                  
                mag_views = []
                view_ids = []
                for store in ormStore.browse(
                    cr, uid, store_ids, context=context):
                    mag_views = websiteAPI.store_views(
                        {'group_id': {'=': store.magento_id}}
                    )
                      
                    # Create stores
                    for mag_view in mag_views:
                        view_ids.append(ormView.find_or_create(
                            cr, uid, store.id, mag_view, context
                        ))
  
                              
#                 #     nonono
#                 raise osv.except_osv( # nonono aaa!!! nonono NONONO
#                     _('Success!'),
#                     _('Import website successfully.')
#                 )
                return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def import_website.')
            )
# #        
        
        return True
    
    def import_category(self, cr, uid, ids, context={}):
        """
        Import any categories following its hierarchy.

        :return: None
        """
        ormWebsite = self.pool.get('crea8s.magento.website')
        ormCategory = self.pool.get('product.category')
        ormCategoryMagento = self.pool.get('crea8s.magento.product_category')
# Create websites  ?????.
# 1. nono-aaa, okok; cause: Core (not 02) ????? nonononono nonononono nonononono nonononono aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
# 2. okok, cause: raise osv.except_osv(... 
        try:
            print 'crea8s_magento_instance.py: def import_category'
            instance = self.browse(cr, uid, ids[0], context)
            context.update({'magento_instance': instance.id})
            
            # loop websites
            arrWebsiteID = ormWebsite.search(cr, uid, [], context=context)
            website = ormWebsite.browse(
                cr, uid, arrWebsiteID ,context
            )
            
            # get category follow websites 
            with magento.Category(
                              instance.url, instance.api_user, instance.api_key
                              ) as category_api:
            
                category_tree = category_api.tree(
                                                  1 #website.magento_root_category_id
                     )
                
#                 category_child = category_api.info(
#                     category_tree['children'][2]['category_id']
#                 )
#                 print '+ category_tree' + str(category_tree)
#                 print '+ category_child' +str(category_child)

                print '+ instance.category' + str(instance.category)
                ormCategory.crea8s_find_or_create_using_magento_data(
                    cr, uid, category_tree, parent=instance.category.id, context=context)
            
            
            # get products 
#             with magento.Product(
#                               instance.url, instance.api_user, instance.api_key
#                               ) as product_api:
#                 product_list = product_api.list(
# #                      website.magento_root_category_id
#                      )
#                 print str(product_list)
                
            return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def import_category.')
            )
            
    
    def import_product(self, cr, uid, ids, context={}): 
        """
        Import Products.

        :return: None
        """
        
        # declare any object ORM
        ormWebsite = self.pool.get('crea8s.magento.website')
        ormCategory = self.pool.get('product.category')
        ormCategoryMagento = self.pool.get('crea8s.magento.product_category')
        product_obj = self.pool.get('product.product')
        mg_product = self.pool.get('crea8s.magento.product')
        
        
# Create websites  ?????.
# 1. nono-aaa, okok; cause: Core (not 02) ????? nonononono nonononono nonononono nonononono aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
# 2. okok, cause: raise osv.except_osv(... 
        try:
            print 'crea8s_magento_instance.py: def import_product'
            
            # update instance for current context
            instance = self.browse(cr, uid, ids[0], context)
            context.update({'magento_instance': instance.id})
            context.update({'magento_website': instance.websites[0].id})  # for only the first website...
            storeview_id = instance.websites[0].stores[0].views[0].id
            storeview_id_magento = instance.websites[0].stores[0].views[0].magento_id
            
            # loop websites
            arrWebsiteID = ormWebsite.search(cr, uid, [], context=context)
            website = ormWebsite.browse(
                cr, uid, arrWebsiteID ,context
            )
            
            # get category follow websites 
            
            with magento.Product(
                              instance.url, instance.api_user, instance.api_key
                              ) as product_api:  # get connection, SLOW!
                
                
                product_list = product_api.list(
#                         store_view=magento_store_id
                ) 
                print '+ product_list' + str(product_list)
                
                for product in product_list:
                    
                    product_api.connect() # okok, before: api.info...
                    product_api.__enter__() # nono, before: api.info...
#                     if product['type'] == 'simple':
                    product_id_magento = product['product_id']
                    product_data = product_api.info(
                        product=product_id_magento,
                    )
                    print '+ product_data' + str(product_data)
                    
                    product_media = product_api.call('product_media.list', [int(product_id_magento)])
                    binary_read_decoded = base64.b64encode('')
                    strURL = ''
                    
                    if len(product_media) > 0:
#                         strURL = product_media[0]['url'] if len(product_media) > 1 else ''
#                         strURL = product_media[0]['url'] 
                        for item in  product_media:
                            if len(item['types']) > 0:
                                if 'image' in item['types']:
                                    strURL = item['url']
                                    
                                    
                                    
                        print '+ strURL: ' + str(strURL)
                        print '+ product_media: ' + str(product_media)
                        if strURL <> '':
                            binary = urllib2.urlopen(strURL)
                            binary_read = binary.read()
                            binary_read_decoded = base64.b64encode(binary_read)
                        
                        # other ways to get encoded image. 
#                         page = urllib.urlretrieve(strURL)
#                         read_data = False
#                         with open(page[0], 'rb') as f:
#                             read_data = f.read()
#                             binary_read_decoded = base64.encodestring(read_data)
                         
                    product_data.update({'image': binary_read_decoded}) # can NOT print 'binary_read_decoded'......
                    product_obj.crea8s_find_or_create_using_magento_data(cr, uid, product_data, context)
                    
            return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            
            _logger.info('import_product-info: FALSE')
            _logger.debug('import_product-debug: FALSE')
            _logger.error('import_product-error: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
            print '===== ===== import_product-info: FALSE'
            _logger.info('import_product-info: FALSE')
            
#             raise osv.except_osv(
#                 _('MAYBE Incorrect API Settings!'),
#                 _('crea8s_magento_instance.py > def import_product.')
#             )
            
            
    def import_customer(self, cr, uid, ids, context={}): 
        """
        Import Partners.

        :return: None
        """
        
        # declare any object ORM
        ormWebsite = self.pool.get('crea8s.magento.website')
        partner_obj = self.pool.get('res.partner')
#         ormCategory = self.pool.get('product.category')
#         ormCategoryMagento = self.pool.get('crea8s.magento.product_category')
#         product_obj = self.pool.get('product.product')
#         ormSaleOrder = self.pool.get('sale.order')
#         mg_product = self.pool.get('crea8s.magento.product')
        
        
# Create websites  ?????.
# 1. nono-aaa, okok; cause: Core (not 02) ????? nonononono nonononono nonononono nonononono aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
# 2. okok, cause: raise osv.except_osv(... 
        try:
            print 'crea8s_magento_instance.py: def import_customer'
            
            # update instance for current context
            instance = self.browse(cr, uid, ids[0], context)
            context.update({'magento_instance': instance.id})
            context.update({'magento_website': instance.websites[0].id})  # for only the first website...
            storeview_id = instance.websites[0].stores[0].views[0].id
            storeview_id_magento = instance.websites[0].stores[0].views[0].magento_id
            web_id_magento = instance.websites[0].magento_id
            
            # loop websites
            arrWebsiteID = ormWebsite.search(cr, uid, [], context=context)
            website = ormWebsite.browse(
                cr, uid, arrWebsiteID ,context
            )
            
            
            iCountCustomer = 0 
            with magento.Customer(
                              instance.url, instance.api_user, instance.api_key
                              ) as cust_api:  # get connection, SLOW!
                
                # order states  
#                 order_states_to_import_in = [
#                     state.code for state in magento_state_obj.browse(
#                         cursor, user, order_states, context=context
#                     )
#                 ]
                filter = {
                    'website_id': {'=': web_id_magento},
#                     'store_id': {'=': storeview_id_magento}, # nonono
#                     'state': {'in': order_states_to_import_in},
                }
                
                cust_list = cust_api.list(filter)
                new_cust = []
                for item in cust_list:
                    iCountCustomer += 1
                    item_full = cust_api.info(item['customer_id'])
                    print '+ item_full: ' + str(item_full)
                    
                    arr_addresses = cust_api.call('customer_address.list', [item['customer_id']])
                    print '+ arr_addresses: ' + str(arr_addresses)
                    for item_address in arr_addresses: 
                        if item_address['is_default_billing'] == True:
                            item_full['address'] = item_address
                            # NO NEED: item_address = cust_api.call('customer_address.info', [item_address['customer_address_id']]) # NOT item['customer_id'] ....NO NEED:
#                     if len(arr_addresses) > 0:
#                         item_full['address'] = arr_addresses[0]
                    
                    objFound = partner_obj.crea8s_find_or_create_using_magento_data(
                            cr, uid,
                            item_full,
                            context,
                        )
                    
                    if objFound == False:
                        new_cust.append(
                            [item['customer_id'], item['firstname'] + ' ' + item['lastname'] ]   
                        )
                        
                
                print '+ cust_list: ' + str(cust_list)
                print '+ new_cust: ' + str(new_cust)
#                 ormSaleOrder.crea8s_find_or_create_using_magento_data(cr, uid, order_data, context)
                
                    
            return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            
            print '+ iCountCustomer: ' + str(iCountCustomer)
            _logger.info('import_partner-info: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
            
            
            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def import_customer.')
            )
           
    
    
    def import_sale_order(self, cr, uid, ids, context={}): 
        """
        Import Sale Orders.

        :return: None
        """
        
        # declare any object ORM
        ormWebsite = self.pool.get('crea8s.magento.website')
        ormSaleOrder = self.pool.get('sale.order')
        
#         ormCategory = self.pool.get('product.category')
#         ormCategoryMagento = self.pool.get('crea8s.magento.product_category')
#         product_obj = self.pool.get('product.product')
#         ormSaleOrder = self.pool.get('sale.order')
#         mg_product = self.pool.get('crea8s.magento.product')
        
        
# Create websites  ?????.
# 1. nono-aaa, okok; cause: Core (not 02) ????? nonononono nonononono nonononono nonononono aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
# 2. okok, cause: raise osv.except_osv(... 
        try:
            print 'crea8s_magento_instance.py: def import_sale_order'
            
            # update instance for current context
            instance = self.browse(cr, uid, ids[0], context)
            context.update({'magento_instance': instance.id})
            context.update({'magento_website': instance.websites[0].id})  # for only the first website...
            context.update({'magento_store': instance.websites[0].stores[0].id})  # for only the first website...
            context.update({'magento_view': instance.websites[0].stores[0].views[0].id})  # for only the first website...
            storeview_id = instance.websites[0].stores[0].views[0].id
            storeview_id_magento = instance.websites[0].stores[0].views[0].magento_id
            
            # loop websites
            arrWebsiteID = ormWebsite.search(cr, uid, [], context=context)
            website = ormWebsite.browse(
                cr, uid, arrWebsiteID ,context
            )
            
            iCountOrder = 0
            with magento.Order(
                              instance.url, instance.api_user, instance.api_key
                              ) as order_api:  # get connection, SLOW!
                 
                # order states  
#                 order_states_to_import_in = [
#                     state.code for state in magento_state_obj.browse(
#                         cursor, user, order_states, context=context
#                     )
#                 ]
                filter = {
                    'store_id': {'=': storeview_id_magento},
#                     'state': {'in': order_states_to_import_in},
                }
#                 filter = {}
                 
                order_list = order_api.list(filter)
#                 print '+ order_list: ' + str(order_list) 
                new_sales = []
                for item in order_list:
                    iCountOrder += 1
#                     if iCountOrder >= 2:
#                         break
                    order_api.connect() # okok, before: api.info...
                    order_api.__enter__() # nono, before: api.info...
                    item_full = order_api.info(item['increment_id'])
#                     print '+ item_full: ' + str(item_full)
                    objFound = ormSaleOrder.crea8s_find_or_create_using_magento_data(
                            cr, uid,
                            item_full,
                            context,
                        )
                
                
#                 print '+ new_sales: ' + str(new_sales) # Calling parameters do not match signature  ????? AAAAA
#                 print '+ new_sales: ' + str('new_sales') # Calling parameters do not match signature  ????? AAAAA ??
                
                    
            return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            
            
            _logger.info('import_sale_order-info: FALSE')
            _logger.debug('import_sale_order-debug: FALSE')
            _logger.error('import_sale_order-error: FALSE')
            _logger.info('import_sale_order-iCountOrder: ' + str(iCountOrder))
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
            print '===== ===== import_sale_order-info: FALSE'
            _logger.info('import_sale_order-info: FALSE')
            
            
            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def import_sale_order.')
            )
            
            
    def import_delivery(self, cr, uid, ids, context={}): 
        """
        Import Delivery...

        :return: None
        """
        
        # declare any object ORM
        ormWebsite = self.pool.get('crea8s.magento.website')
        ormDelivery = self.pool.get('stock.picking') 
        ormDeliMagento = self.pool.get('stock.picking.magento') 
        
        try:
            print 'crea8s_magento_instance.py: def import_delivery'
            
            # update instance for current context
            instance = self.browse(cr, uid, ids[0], context)
            context.update({'magento_instance': instance.id})
            context.update({'magento_website': instance.websites[0].id})  # for only the first website...
            context.update({'magento_store': instance.websites[0].stores[0].id})  # for only the first one...
            
            iCountOrder = 0
            ormDeliMagento.crea8s_print_text('phongnd', context)
            
            # maybe occur error:  must be called with Delivery instance as first argument (got str instance instead)
            # compare vs ormStock without ... _table = "stock_picking"
            Delivery.crea8s_print_text(ormDeliMagento, 'strText', context)  
            
            with magento.Shipment(
                              instance.url, instance.api_user, instance.api_key
                              ) as deli_api:  # get connection, SLOW!
                
                filter = {}
                deli_list = deli_api.list(filter)
#                 print '+ deli_list: ' + str(deli_list) 
 
                for item in deli_list:
                    iCountOrder += 1
#                     if iCountOrder >= 2:
#                         break
                    deli_api.connect() # okok, before: api.info...
                    deli_api.__enter__() # nono, before: api.info...
                    item_full = deli_api.info(item['increment_id'])  # shipment_id  +  increment_id  
                    print '+ item_full: ' + str(item_full)  
                    
                    context.update({'shipment_id': item_full['shipment_id']})  # for only the first website...
                    objFound = ormDeliMagento.crea8s_find_or_create_using_magento_data(
                            cr, uid,
                            item_full,
                            context,
                        )
#                 
                #testing ORM model. 
#                 print '+ new_deliverys: ' + str(new_deliverys) # Calling parameters do not match signature  ????? AAAAA
#                 print '+ new_deliverys: ' + str('new_deliverys') # Calling parameters do not match signature  ????? AAAAA ??
                
                
            
            return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            
            _logger.info('import_delivery-info: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
            
            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def import_delivery.')
            ) 
        
        
        
    def import_sale_invoice(self, cr, uid, ids, context={}): 
        """
        Import Sale Invoice...

        :return: None
        """
        
        # declare any object ORM
        ormWebsite = self.pool.get('crea8s.magento.website')
        inv_obj = self.pool.get('account.invoice') 
        
        try:
            print 'crea8s_magento_instance.py: def import_sale_invoice'
            
            # update instance for current context
            instance = self.browse(cr, uid, ids[0], context)
            context.update({'magento_instance': instance.id})
            context.update({'magento_website': instance.websites[0].id})  # for only the first website...
            
            
            # import Payment by SOs
            self.import_payment_by_SO(cr, uid, ids, context)
             
#              
#             iCountOrder = 0
#             with magento.Invoice(
#                               instance.url, instance.api_user, instance.api_key
#                               ) as invoice_api:  # get connection, SLOW!
#                  
#                 filter = {}
#                 inv_list = invoice_api.list(filter)
#                 print '+ inv_list: ' + str(inv_list) 
# #                 new_sales = []
#                 for item in inv_list:
#                     iCountOrder += 1
# #                     if iCountOrder >= 2:
# #                         break
#                     invoice_api.connect() # okok, before: api.info...
#                     invoice_api.__enter__() # nono, before: api.info...
#                     item_full = invoice_api.info(item['increment_id'])
# #                     print '+ item_full: ' + str(item_full)  
#                     objFound = inv_obj.crea8s_find_or_create_using_magento_data(
#                             cr, uid,
#                             item_full,
#                             context,
#                         )
                    
                 
#                 print '+ new_sales: ' + str(new_sales) # Calling parameters do not match signature  ????? AAAAA
#                 print '+ new_sales: ' + str('new_sales') # Calling parameters do not match signature  ????? AAAAA ??
                
                
            
            return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            
            _logger.info('import_sale_invoice-info: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
            
            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def import_sale_invoice.')
            ) 
        
        
    
    def import_payment_by_SO(self, cr, uid, ids, context={}): 
        """
        Import Payment...

        :return: None
        """
        
        # declare any object ORM
        ormWebsite = self.pool.get('crea8s.magento.website')
        inv_obj = self.pool.get('account.voucher') 
        print 'crea8s_magento_instance.py: def import_payment_by_SO etc...'
        
        try:
            
            
            # update instance for current context
            instance = self.browse(cr, uid, ids[0], context)
            context.update({'magento_instance': instance.id})
            context.update({'magento_website': instance.websites[0].id})  # for only the first website...
            
            
#             iCountOrder = 0
#             with magento.Invoice(
#                               instance.url, instance.api_user, instance.api_key
#                               ) as invoice_api:  # get connection, SLOW!
#                  
#                 filter = {}
#                 inv_list = invoice_api.list(filter)
#                 print '+ inv_list: ' + str(inv_list) 
# #                 new_sales = []
#                 for item in inv_list:
#                     iCountOrder += 1
# #                     if iCountOrder >= 2:
# #                         break
#                     invoice_api.connect() # okok, before: api.info...
#                     invoice_api.__enter__() # nono, before: api.info...
#                     item_full = invoice_api.info(item['increment_id'])
# #                     print '+ item_full: ' + str(item_full)  
#                     objFound = inv_obj.crea8s_find_or_create_using_magento_data(
#                             cr, uid,
#                             item_full,
#                             context,
#                         )
                    
                 
#                 print '+ new_sales: ' + str(new_sales) # Calling parameters do not match signature  ????? AAAAA
#                 print '+ new_sales: ' + str('new_sales') # Calling parameters do not match signature  ????? AAAAA ??
                
                
            
            return True
        except (
            xmlrpclib.Fault, IOError,
            xmlrpclib.ProtocolError, socket.timeout
            ):
            
            _logger.info('import_payment_by_SO-info: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
            
            raise osv.except_osv(
                _('MAYBE Incorrect API Settings!'),
                _('crea8s_magento_instance.py > def import_payment_by_SO') 
            ) 
        
        
        
        
Instance()





#             """ Map a record and check the result """
#             class MyMapper(ImportMapper):
#             
#                 direct = [('name', 'out_name')]
#             
#                 @mapping
#                 def street(self, record):
#                     return {'out_street': record['street'].upper()}
#             
# #             env = mock.MagicMock()
# #             backend_record = session.browse('magento.backend', backend_id)
#             
#             # backend_record.version  === 1.7
#             # service(=== _backend_type)
#             self._backend_type = 'magento' #AAAA  
#             
# #             instance.context = context
#             env = Environment(instance, self, 'account.invoice')
#             record = {'name': 'Guewen',
#                         'street': 'street'}
#             mapper = MyMapper(env)
#             mapper.convert(record)
#             expected = {'out_name': 'Guewen',
#                         'out_street': 'STREET'}
#             
#             print '+ ' + str(mapper.data)
#             print '+ ' + str(mapper.data_for_create)
#             print '+ ' + str(expected)
# #             self.assertEqual(mapper.data, expected)
# #             self.assertEqual(mapper.data_for_create, expected)



